package com.sduept.nwld.dataserver.controller.equipment.assessment;

import com.alibaba.fastjson.JSONObject;
import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.document.dto.RecordImageDTO;
import com.sduept.bigdata.document.entity.core.RecordImage;
import com.sduept.bigdata.document.enums.AttachmentType;
import com.sduept.bigdata.equipment.assessment.dto.CimObjectDTO;
import com.sduept.bigdata.equipment.assessment.dto.EquipmentDTO;
import com.sduept.bigdata.equipment.assessment.exception.ParameterException;
import com.sduept.bigdata.equipment.assessment.model.hiddendanger.track.HiddenDangerTrack;
import com.sduept.bigdata.equipment.assessment.model.inspection.*;
import com.sduept.bigdata.equipment.assessment.model.problembase.ProblemBase;
import com.sduept.bigdata.equipment.assessment.service.*;
import com.sduept.bigdata.equipment.assessment.service.impl.DeductionTaskService;
import com.sduept.cim.model.core.Substation;
import com.sduept.cim.model.protection.ProtectionEquipment;
import com.sduept.cim.model.wires.*;
import com.sduept.core.entity.AbstractStandardDict;
import com.sduept.core.entity.IdentifiedObject;
import com.sduept.core.service.StandardDictService;
import com.sduept.core.service.impl.StandardDictConfigurator;
import com.sduept.generator.ObjectId;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.bigdata.weather.map.MapDataCache;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.nwld.dataserver.manager.protection.SpecialReportManager;
import com.sduept.permission.entity.PersonnelEntityBean;
import com.sduept.utils.Base64;
import com.sduept.utils.PingYinUtil;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.PrimeFaces;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.util.*;


/**
 * 问题设备信息controller类
 */
@Named
@ViewScoped
public class QuestionEquipmentController  extends AbstractController{

	private static final long serialVersionUID = 4163439950615045657L;

	@Autowired
	private InspectionQuestionEquipmentService equipmentService;
	@Autowired
	private InspectionItemService itemService;
	@Autowired
	private CimManager cimMan;
	@Autowired
	private MapDataCache cimChe;
	@Autowired
	private InspectionStationService stationService;
	@Autowired
	private InspectionPlanService planService;
	@Autowired
	private HiddenDangerTrackService trackService;
	@Autowired
	private InspectionExpertService expertService;
	@Autowired
	private StandardDictConfigurator sdc;
	@Autowired
	private StandardDictService sman;
	@Autowired
	private ProblemBaseService problemService;
    @Autowired
	private SpecialReportManager srm;
    @Autowired
	private InspectionDocumentService docService;
    @Autowired
	private CommonDocumentProperties commonDocumentProperties;
    @Autowired
   	private AssessmentCimModelService modelService;
    @Autowired
   	private AssessmentCimService assessmentCimService;
    @Autowired
    private DeductionTaskService deductService;
	/**
	 * dataTable展示的集合,根据检查项查出  用于问题设备的table显示
	 */
	private List<InspectionQuestionEquipment> quesEquipments = new ArrayList<InspectionQuestionEquipment>();
	private float oldQuesDeduct=0.0f;
	private List<InspectionQuestionEquipment> quesEquipmentFromDB = new ArrayList<InspectionQuestionEquipment>();

	/**
	 * 字典库map 
	 */
    private Map<String, List<String>> discMap = null;//字典map
    private List<String> quesList ; // 问题归类
	private List<String> reasonList ;//原因归类
	private List<String> gradeList ; // 隐患等级
    private List<String> sourceList; // 隐患来源
    
	/**
	 * 保护设备
	 */
	private List<ProtectionEquipment> allCims = new ArrayList<ProtectionEquipment>();
	/**
	 * 存放设备名及对应的设备id
	 */
	private Map<String,String>  equipmentMap = new HashMap<String,String>();
	/**
	 * 单选框菜单
	 */
	private List<String> selectMenu = new ArrayList<String>();
	/**
	 * 点击保存时回传的数据 拼接到问题描述上
	 */
	private String descData = "{}";
	/**
	 * 根据传递的stationId获得评价计划
	 */
	private InspectionPlan plan;
	/**
	 * 根据传递的itemId获得评价项目
	 */
	private InspectionItem currentInspectionItem;
	/**
	 * 当前评价项所属的评价厂站
	 */
	private InspectionStation currentInspectionStation;
	/**
	 * 当前登录的专家
	 */
	private InspectionExpert currentExpert;
	/**
	 * 检查项id
	 */
	private String itemId;
	/**
	 * 评价厂站id
	 */
	private String inspectionStationId;
	/**
	 * 变电站id
	 */
	private String stationId;
	private String index;
	
	private String planId;
	/**
	 * 继承自字典库
	 */
    private Class<? extends AbstractStandardDict> T = null;	
    private  String quesDeviceId;//问题设备ID
    private  String quesDevice;//问题设备
    private  int quesDeviceNum;//问题数量
    private String deductionCriteria;//扣分标准
	
    private RecordImageDTO newImageDto;
    private List<RecordImageDTO> newImageDtos;
    /**
     * 当前InspectionItem所对应的问题设备，以及问题设备最新上传的图片或视频
     */
    private Map<InspectionQuestionEquipment,List<RecordImageDTO>> equipmentAndNewImageMap;
    private String alertMsg = null;
    private List<InspectionQuestionEquipment> errorList;
    private InspectionQuestionEquipment selectedEquipment;
    
    /**
     * 设备选择器-设备树根节点
     */
    private TreeNode root;
    private TreeNode[] selectedNodes;
    public static final String TREE_TYPE_Equipment = "Equipment";
	public static final String TREE_TYPE_Dir = "1";
	
	//所有的自定义问题设备
//	private List<CustomQuestionEquipment> customQuesEquipments = new ArrayList<CustomQuestionEquipment>();
	//自定义设备名称
//	private String customQuesEquipmentName;
	//设备查询
	private String equipmentQuery;
	//保存所有的设备节点
	private List<TreeNode> equipmentTreeNodes = new ArrayList<TreeNode>();
	
	
	@PostConstruct
	public void init()  {
		itemId = getParameter("itemId");
		inspectionStationId = getParameter("stationId");
		stationId = getParameter("planStationId");
		planId=getParameter("planId");
		index = getParameter("index");
		deductionCriteria=getParameter("deductionCriteria");
		initPlanAndItem();
//		initEquipmentMap();
		initRoot();
//		initCustomQuestionEquipments();
		initQuestionTable();
		initDics();
		genEquipmentAndImageMap();
	}
    
	private void initPlanAndItem() {
		 try {
			 plan = planService.findById(planId);
			 currentInspectionStation = stationService.findById(inspectionStationId);
			 currentInspectionItem = itemService.findById(itemId);
			 currentExpert = expertService.findByCode(getCurrentUser().getCode());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 初始化设备选择器树节点
	 */
	private void initRoot() {
		equipmentTreeNodes.clear();
		root = new DefaultTreeNode();
		TreeNode rnode = new DefaultTreeNode(TREE_TYPE_Dir,"变电站",root);
		Substation station = cimChe.getStationid_map().get(stationId);
		if(station!=null) {
			// <"直流线路", List<EquipmentDTO>>;
			Map<String, List<EquipmentDTO>> map = assessmentCimService.findEquipmentAndTypeMapByStation(stationId);
			TreeNode subNode = new DefaultTreeNode(Substation.class.getSimpleName(),station,rnode);
			List<EquipmentDTO> dtos = null;
			List<String> equipmentTypeNames = assessmentCimService.findAllEquipmentName();
			for (String type : equipmentTypeNames) {
				TreeNode node = new DefaultTreeNode(TREE_TYPE_Dir, type, subNode);
				dtos = map.get(type);
				if(null != dtos && dtos.size()>0) {
					for (EquipmentDTO equipmentDTO : dtos) {
						TreeNode equipmentNode = new DefaultTreeNode(TREE_TYPE_Equipment, equipmentDTO, node);
						equipmentTreeNodes.add(equipmentNode);
					}
				}
			}
			subNode.setExpanded(true);
		}
		rnode.setExpanded(true);
		
	}
	/**
	 * 初始化自定义问题设备
	 */
//	private void initCustomQuestionEquipments() {
//		try {
//			customQuesEquipments = sman.findAll(CustomQuestionEquipment.class);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
	public boolean showChooseBtn() {
//		if (selectedNode != null){
//			if(TREE_TYPE_Equipment.equals(selectedNode.getType())
//					|| (Substation.class.getSimpleName().equals(selectedNode.getType()))) {
//				return true;
//			}
//		}
		if(selectedNodes!=null&&selectedNodes.length>0) {
			return true;
		}
		return false;
	}
	
//	public List<String> completeCustomEquipmentNames(String query) {
//		List<String> result = new ArrayList<String>();
//		if(StringUtils.isNotBlank(query)) {
//			for(CustomQuestionEquipment cus : customQuesEquipments) {
//				if(PingYinUtil.getPingYinHeader(cus.getName()).startsWith(query)) {//根据拼音首字母
//					result.add(cus.getName());
//				}
//				if(cus.getName().contains(query)) {
//					if(!result.contains(cus.getName())) {
//						result.add(cus.getName());
//					}
//				}
//			}
//		}
//		return result;
//	}
	
	public List<String> completeEquipmentNames(String query) {
		List<String> result = new ArrayList<String>();
		List<EquipmentDTO> equipmentDtos = assessmentCimService.findEquipmentDTOsByStation(stationId);
		if(StringUtils.isNotBlank(query)) {
			for(EquipmentDTO dto : equipmentDtos) {
				if(PingYinUtil.getPingYinHeader(dto.getName()).startsWith(query)) {//根据拼音首字母
					result.add(dto.getName());
				}
				if(dto.getName().contains(query)) {
					if(!result.contains(dto.getName())) {
						result.add(dto.getName());
					}
				}
			}
		}
		return result;
	}
	/**
	 * 重新生成设备选择树
	 */
	public void reGenerateTree() {
		if(StringUtils.isNotBlank(equipmentQuery)) {
			root = new DefaultTreeNode();
			root.setExpanded(true);
			TreeNode rnode = new DefaultTreeNode(TREE_TYPE_Dir,"变电站",root);
			rnode.setExpanded(true);
			Substation station = cimChe.getStationid_map().get(stationId);
			if(station!=null) {
				TreeNode subNode = new DefaultTreeNode(Substation.class.getSimpleName(),station,rnode);
				subNode.setExpanded(true);
				for(TreeNode equipmentNode : equipmentTreeNodes) {
					EquipmentDTO equipmentDto = (EquipmentDTO) equipmentNode.getData();
					if(equipmentQuery.equals(equipmentDto.getName())) {
						TreeNode parent = equipmentNode.getParent();
						DefaultTreeNode pNode = new DefaultTreeNode(parent.getType(),parent.getData(),subNode);
						pNode.setExpanded(true);
						new DefaultTreeNode(equipmentNode.getType(),equipmentNode.getData(),pNode);
					}
				}
			}
			
		}
	}
	public void resetEquipmentQuery() {
		initRoot();
		equipmentQuery = null;
	}
	/**
	 * 通过设备选择器树选择设备
	 */
	public void makeSureEquipmentByTree() {
		for(int i=0;i<selectedNodes.length;i++) {
//			if(selectedNode.getType().equals(Substation.class.getSimpleName())) {
//				Substation sub = (Substation) selectedNode.getData();
//				addQuestionEquipment(sub.getId(), sub.getName());
//			}else 
			if(selectedNodes[i].getType().equals(TREE_TYPE_Equipment)) {
				EquipmentDTO data = (EquipmentDTO) selectedNodes[i].getData();
				addQuestionEquipment(data.getId(), data.getName());
			}
		}
		
	}
	/**
	 * 自定义问题设备
	 */
//	public void makeSureEquipmentByCustom() {
//		if(StringUtils.isBlank(customQuesEquipmentName)) {
//			alertErrorMessage("请先输入自定义设备名称！");
//			return;
//		}
//		CustomQuestionEquipment quesEquip = null;
//		for(CustomQuestionEquipment cqe : customQuesEquipments) {
//			if(cqe.getName().equals(customQuesEquipmentName)) {
//				quesEquip = cqe;
//				break;
//			}
//		}
//		if(quesEquip==null) {
//			quesEquip = new CustomQuestionEquipment();
//			quesEquip.setId(ObjectId.get().toString());
//			quesEquip.setName(customQuesEquipmentName);
//			//保存数据库
//			try {
//				sman.createOrUpdate(quesEquip);
//				customQuesEquipments.add(quesEquip);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//		addQuestionEquipment(quesEquip.getId(), quesEquip.getName());
//		//关闭设备选择弹窗
//		PrimeFaces.current().executeScript("PF('equipmentSelector').hide()");
//	}
	/**
	 * 初始化设备map 供设备选择框使用
	 * @throws ParameterException 
	 */
    private void initEquipmentMap() {
    	CimObjectDTO cim = null;
    	try {
			 cim = stationService.findCimObjectByID(stationId);
		} catch (ParameterException e) {
			e.printStackTrace();
		}
    	if (cim.breakers.size()>0) {
    		for (Breaker a : cim.breakers) {
    			selectMenu.add(a.getName());
    			equipmentMap.put(a.getName(),a.getId());
			}
		}
    	if(cim.busbars.size()>0) {
    		for (BusbarSection b : cim.busbars) {
    			selectMenu.add(b.getName());
    			equipmentMap.put(b.getName(),b.getId());
			}
    	}
    	if(cim.compensators.size()>0) {
    		for (Compensator c : cim.compensators) {
    			selectMenu.add(c.getName());
    			equipmentMap.put(c.getName(),c.getId());
			}
    	}
    	if(cim.disconnectors.size()>0) {
    		for (Disconnector d : cim.disconnectors) {
    			selectMenu.add(d.getName());
    			equipmentMap.put(d.getName(),d.getId());
    			
			}
    	}
    	if(cim.groundDisconnectors.size()>0) {
    		for (GroundDisconnector g : cim.groundDisconnectors) {
    			selectMenu.add(g.getName());
    			equipmentMap.put(g.getName(),g.getId());
			}
    	}
    	if(cim.grounds.size()>0) {
    		for (Ground gd : cim.grounds) {
    			selectMenu.add(gd.getName());
    			equipmentMap.put(gd.getName(),gd.getId());
			}
         }
	}

	/**
	 * 根据itemid初始化问题设备和其他问题
	 */
	private void initQuestionTable() {
		try {
			quesEquipments = equipmentService.findByInspectionItem(itemId);
			if(quesEquipments!=null && !quesEquipments.isEmpty()) {
				for(InspectionQuestionEquipment quesEquipment:quesEquipments) {
					oldQuesDeduct+=quesEquipment.getQuesDeduct();
				}		
			}
			quesEquipmentFromDB.addAll(quesEquipments);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	 /**
     * 初始化字典Map
     */
	@SuppressWarnings("unchecked")
	private void initDics() {
		discMap = new HashMap<String, List<String>>();
		List<String> dicts = Arrays.asList("HiddenDangerQuesType","HiddenDangerReasonType","HiddenDangerLevel"	,"HiddenDangerSource");
		try {
			for (String className : dicts) {
				T=sdc.getT(className);
				List<AbstractStandardDict> dictList = (List<AbstractStandardDict>) sman.findAll(Class.forName(T.getName()));
				List<String> values = new ArrayList<String>();
				for (AbstractStandardDict d : dictList) {
					values.add(d.getName());
				}
				discMap.put(className, values);
			}
		} catch (Exception e) {
			addErrorMessage("字典库加载失败");
			e.printStackTrace();
		}
		quesList = discMap.get("HiddenDangerQuesType");
		reasonList = discMap.get("HiddenDangerReasonType");
		gradeList = discMap.get("HiddenDangerLevel");
		sourceList = discMap.get("HiddenDangerSource");
		
	}

	/**
	 * 保存问题设备
	 */
	//TODO  需要优化保存逻辑，提供自动更新保存
	public void save() {// 改成change事件保存 保存的是问题设备等信息 此保存用于拼接和传递参数

		errorList = new ArrayList<InspectionQuestionEquipment>();
		for (InspectionQuestionEquipment qe : equipmentAndNewImageMap.keySet()) {
			qe.setUpdateTime(new Date().getTime());
//			qe.setQuesDeduct(qe.getQuestionAmount()*Float.parseFloat(deductionCriteria));
			// 图片数量>=问题设备数量，直接进行保存
			if(imagesMoreThanEquipments(qe)) {
				try {
					equipmentService.createOrUpdate(qe);
					List<RecordImageDTO> images = equipmentAndNewImageMap.get(qe);
					for (RecordImageDTO recordImageDTO : images) {
						docService.upload(recordImageDTO);
					}
				} catch (Exception e) {
					e.printStackTrace();
					addErrorMessage("保存失败");
				}
			} else {
				errorList.add(qe);
			}
		}
		if(errorList.size()>0) {
			StringBuffer alertMsgs = new StringBuffer();
			for (InspectionQuestionEquipment qe : errorList) {
				alertMsgs.append(qe.getEquipmentName() + "、");
			}
			alertMsgs.append("等问题设备数量和上传图片、视频的数量不符，继续保存吗?");
			alertMsg = alertMsgs.toString();
			PrimeFaces.current().executeScript("PF('saveConfirmDialog').show()");
		} else {
			addSuccessMessage("保存成功");
			PrimeFaces.current().executeScript("closeAndSave()");
		}
		JSONObject r = new JSONObject();
		r.put("itemId", itemId);
		r.put("index", index);
		r.put("oldQuesDeduct", oldQuesDeduct);
		descData = r.toJSONString();
	}
	
	/**
     * 更新问题设备数量change事件
     * @param quesEquipment
     * @param count
     */
//	public void onChange(InspectionQuestionEquipment quesEquipment,int count) {
//		if(equipmentAndNewImageMap.containsKey(quesEquipment)) {
//			List<RecordImageDTO> lt = equipmentAndNewImageMap.get(quesEquipment);
//			equipmentAndNewImageMap.remove(quesEquipment);
//			quesEquipment.setQuestionAmount(count);
//			equipmentAndNewImageMap.put(quesEquipment, lt);
//		}
//	}
	
	/**
	 * 当问题设备数量>上传的图片、视频数量时，用户确定保存所调用的方法
	 */
	public void continueSave() {
		for (InspectionQuestionEquipment qe : errorList) {
			try {
				equipmentService.createOrUpdate(qe);
				List<RecordImageDTO> images = equipmentAndNewImageMap.get(qe);
				for (RecordImageDTO recordImageDTO : images) {
					docService.upload(recordImageDTO);
				}
			} catch (Exception e) {
				e.printStackTrace();
				addErrorMessage("保存失败");
			}
		}
		addSuccessMessage("保存成功");
	}
	/**
	 * 判断图片数量是否大于问题设备数量
	 * @param quesEquipment
	 * @return 图片数量<问题设备数量,返回false;
	 * @return 图片数量>=问题设备数量,返回true;
	 */
	public boolean imagesMoreThanEquipments(InspectionQuestionEquipment quesEquipment) {
		// 首先获取已有的图片数量
		int imageTotal = 0;
		try {
			List<RecordImage> oldImages = docService.findRecordImageIdByOid(quesEquipment.getId());
			if(null != oldImages) {
				imageTotal += oldImages.size();
			}
		} catch (Exception e1) {
			e1.printStackTrace();
			addErrorMessage("获取设备的图片或视频时出错");
		}
		// 获取新上传的图片
		List<RecordImageDTO> newImages = equipmentAndNewImageMap.get(quesEquipment);
		if(null != newImages) {
			imageTotal += newImages.size();
		}
		int questionAmount = quesEquipment.getQuestionAmount();
		if(imageTotal<questionAmount) {
			return false;
		} else {
			return true;
		}
	}
	
	public void preEdit(InspectionQuestionEquipment qe) {
		selectedEquipment = qe;
	}
	
	public void onQuestionAmountChange() {
		float deduct = selectedEquipment.getQuestionAmount()*Float.parseFloat(deductionCriteria);
		selectedEquipment.setQuesDeduct(deduct);
	}
	
	public void saveEdit() {
		if(equipmentAndNewImageMap.containsKey(selectedEquipment)) {
			List<RecordImageDTO> lt = equipmentAndNewImageMap.get(selectedEquipment);
			equipmentAndNewImageMap.remove(selectedEquipment);
//			quesEquipment.setQuestionAmount(count);
			equipmentAndNewImageMap.put(selectedEquipment, lt);
		}
	}
	/**
	 * 删除传入的问题设备
	 * @param eq
	 */
	public void delete(InspectionQuestionEquipment eq) {
		if(quesEquipmentFromDB.contains(eq)) {
			try {
				equipmentService.delete(eq.getId());
				quesEquipmentFromDB.remove(eq);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		quesEquipments.remove(eq);
		equipmentAndNewImageMap.remove(eq);
		// 同时删除该问题设备的图片
		deleteImageByQuesEquipment(eq);
		addSuccessMessage("删除成功！");
	}
	
	// 打开选择设备模态框
	public void getEquipmentByStation() {
		Map<String, Object> options = new HashMap<String, Object>();
		options.put("resizable", true);
		options.put("draggable", true);
		options.put("modal", true);
		options.put("width", 600);
		options.put("height", 400);
		Map<String, List<String>> params = new HashMap<>();
		params.put("chooseStation", Arrays.asList("false"));
		//openDialog("/ui/common/equipment_selector_single",  params,options);
		PrimeFaces.current().dialog().openDynamic("/ui/common/equipment_selector_single",  options,params);
	}

	/**
	 * 故障设备选择
	 */
	public void onQuesDeviceChosen(SelectEvent event) {
		IdentifiedObject equipment = (IdentifiedObject) event.getObject();
		quesDevice = equipment.getName();
	}
	/**
	 * 导入问题库
	 * 
	 * @param quesEquipment
	 */
//	public void addToProblemBase(InspectionQuestionEquipment quesEquipment) {
//		ProblemBase base = new ProblemBase();
//		PersonnelEntityBean user = getCurrentUser();
//		base.setCreaterCode(user.getCode());
//		base.setCreaterName(user.getName());
//		base.setCreateTime(new Date());
//		base.setProblemDescription(quesEquipment.getHiddenDangerDesc());
//		//自查、互查
//		base.setProblemSources(plan.getInspectionType().getName());
//		problemService.createOrUpdate(base);
//		addSuccessMessage("成功导入问题库");
//	}

	/**
	 * 生成隐患追踪
	 * 
	 * @param eq
	 */
//	public void generateHiddenDangerTrack(InspectionQuestionEquipment quesEquipment) {
//		HiddenDangerTrack track = null;
//		try {
//			// 查找该问题是否已存在隐患追踪
//			track = trackService.findByQuesEquipmentId(quesEquipment.getId());
//			if (track == null) {// 评分标准和表单规范号的获取
//				String specificationNumber = " ";// 表单规范号 由检查标准序号+检查要素及要求序号组成 1.1-2/1.1.1
//				track = new HiddenDangerTrack(plan.getId(), specificationNumber, plan.getName(), plan.getName(),
//						currentInspectionItem.getName(), itemId, quesEquipment.getId(),
//					    currentInspectionStation.getName(),
//						String.valueOf(currentInspectionStation.getVoltagelevel()), quesEquipment.getName(),
//						currentExpert.getName(), currentExpert.getTelephone(),
//						currentInspectionStation.getStationPersonnel(),
//						currentInspectionStation.getStationPersonnelPhone(),  quesEquipment.getHiddenDangerDesc(), "评分标准",
//						currentInspectionItem.getRectificationPlan(), plan.getResponsible());
//				trackService.createOrUpdate(track);
//			} else {
//				track.setHiddenDangerDesc(quesEquipment.getHiddenDangerDesc());
//				track.setProblemEquipment(quesEquipment.getName());
//				trackService.createOrUpdate(track);
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		addSuccessMessage("成功生成隐患追踪");
//	}
	
	/**
	 * 设备名称选择处理函数
	 * @param event
	 */
	public void onChooseEquipment(InspectionQuestionEquipment eq) {
		if(StringUtils.isNotBlank(eq.getEquipmentName())) {
			String equipmentId = equipmentMap.get(eq.getEquipmentName());
			eq.setEquipmentId(equipmentId);
			eq.setStatus(1);
		}else {
			eq.setStatus(0);
		}
		
	}
	
	/**
	 * 更新问题设备记录和隐患追踪记录
	 * @param item
	 * @throws Exception
	 */
	public void itemSelect(InspectionQuestionEquipment item) throws Exception {
		if(item.getHiddenDangerDesc()==null) {
			return;
		}
		HiddenDangerTrack track = trackService.findByQuesEquipmentId(item.getId());
		if(track!=null) {
			track.setProblemEquipment(item.getName());
			trackService.createOrUpdate(track);
		}
		try {
			equipmentService.createOrUpdate(item);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * change事件  用于创建隐患追踪记录、问题库记录、问题设备表记录
	 * @param quesEquipment
	 * @throws ParameterException
	 */
   public void onDescChange(InspectionQuestionEquipment quesEquipment) throws ParameterException {//有隐患描述就创建一条隐患追踪记录
	   try {
			equipmentService.createOrUpdate(quesEquipment);
		} catch (Exception e) {
			e.printStackTrace();
		}
   }
    /**
     * 生成问题设备表记录
     * @param quesEquipment
     */
	private void createQuenEquipment(InspectionQuestionEquipment quesEquipment) {
		try {
			equipmentService.createOrUpdate(quesEquipment);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 创建问题库记录
	 * @param quesEquipment
	 */
   private void createQuestionItem(InspectionQuestionEquipment quesEquipment) {
	  if(quesEquipment.getHiddenDangerDesc()!=null) {
		  //判断有没有此信息       
		   ProblemBase base = problemService.findByDesc(quesEquipment.getHiddenDangerDesc()); 
		   if(Objects.nonNull(base)) {
			   return;
		   }
		   PersonnelEntityBean user = getCurrentUser();
		   base = new ProblemBase();
		   base.setCreaterCode(user.getCode());
		   base.setCreaterName(user.getName());
		   base.setCreateTime(new Date());
		   base.setProblemDescription(quesEquipment.getHiddenDangerDesc());
		   problemService.createOrUpdate(base);
	  }
	
    }

	//itemSelect事件  点选了就更新问题设备表记录和隐患追踪记录，是否更新的判断：隐患描述为空不生成（不更新） 不为空就更新点选信息
private void createHiddenDangerTrack(InspectionPlan plan, InspectionItem item, InspectionQuestionEquipment quesEquipment)  {
		String planId = plan.getId();
		HiddenDangerTrack track = null;
		try {
			track = trackService.findByQuesEquipmentId(quesEquipment.getId());
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		if(track==null) {//评分标准和表单规范号的获取
			InspectionStation station = stationService.findById(inspectionStationId);
				InspectionExpert expert = null;
				try {
					expert = expertService.findById(item.getActualAssessmentExpertId());//model.getExpertId()
				} catch (Exception e1) {
					addErrorMessage("无评价专家");
					e1.printStackTrace();
				}
				String specificationNumber = " ";//表单规范号   由检查标准序号+检查要素及要求序号组成   1.1-2/1.1.1
				track = new HiddenDangerTrack(  planId, specificationNumber, plan.getName(), plan.getName()
						, item.getName(), itemId, quesEquipment.getId(), station.getName(), String.valueOf(station.getVoltagelevel())
						, quesEquipment.getName(), expert.getName(), expert.getTelephone(), station.getStationPersonnel()
						,  station.getStationPersonnelPhone(), quesEquipment.getHiddenDangerDesc(),  "评分标准"
					    , item.getRectificationPlan(), plan.getResponsible());
				 try {
					 HiddenDangerTrack dt = trackService.createOrUpdate(track);
//					 trackId.append(dt.getId()+";");
				} catch (Exception e) {
					e.printStackTrace();
				}
		}else {
			track.setHiddenDangerDesc(quesEquipment.getHiddenDangerDesc());
			track.setProblemEquipment(quesEquipment.getName());
			try {
				trackService.createOrUpdate(track);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}		
	}
	
public void onQuestionDialogReturn() throws Exception {
	//更新隐患描述
	String data = getParameter("data");
	String modelId = getParameter("descId");
	List<InspectionQuestionEquipment> allQuesList = new ArrayList<InspectionQuestionEquipment>();
//	allQuesList.addAll(otherQuestions);
	allQuesList.addAll(quesEquipments);
	for (InspectionQuestionEquipment eq : allQuesList) {
		if(modelId.equals(eq.getId())) {
			if(eq.getStatus()==1) {
				int index = quesEquipments.indexOf(eq);
				eq.setHiddenDangerDesc(data);;
				quesEquipments.set(index, eq);
			}else {
//				int index = otherQuestions.indexOf(eq);
				eq.setHiddenDangerDesc(data);;
//				otherQuestions.set(index, eq);
			}
			
				/*
				 * if(!data.isEmpty()) { createHiddenDangerTrack(plan,currentInspectionItem,
				 * eq); }
				 */
			break;
		}
	}
	PrimeFaces.current().ajax().update(Arrays.asList("tableForm:datbOther","tableForm:datb"));
}


	public void onQuesDeviceDialogReturn() throws Exception {		
		String data = getParameter("data");
		JSONObject jo=JSONObject.parseObject(data);
		quesDevice=jo.getString("name");
		quesDeviceId=jo.getString("id");	
		addQuestionEquipment();
		PrimeFaces.current().ajax().update(Arrays.asList("tableForm:datb"));
	}
	 /**
	  * 添加问题设备
     */
	public void addQuestionEquipment() {
		try {
			InspectionQuestionEquipment eq = new InspectionQuestionEquipment();
			eq.setId(ObjectId.get().toString());
			eq.setInspectionItem(currentInspectionItem);
//			eq.setEquipmentId(quesDeviceId);
//			eq.setEquipmentName(quesDevice);
			eq.setInspectionStationId(currentInspectionStation.getId());
			eq.setStationId(currentInspectionStation.getStationId());
			eq.setStationName(currentInspectionStation.getStationName());	
			//默认问题数量为1
			eq.setQuestionAmount(1);
			eq.setPlanId(planId);
			eq.setQuesDeduct(eq.getQuestionAmount()* Float.parseFloat(deductionCriteria));
			
			quesEquipments.add(eq);
			equipmentAndNewImageMap.put(eq, new ArrayList<RecordImageDTO>());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void addQuestionEquipment(String equipmentId,String equipmentName) {
		try {
			InspectionQuestionEquipment eq = new InspectionQuestionEquipment();
			eq.setId(ObjectId.get().toString());
			eq.setInspectionItem(currentInspectionItem);
			eq.setEquipmentId(equipmentId);
			eq.setEquipmentName(equipmentName);
			eq.setInspectionStationId(currentInspectionStation.getId());
			eq.setStationId(currentInspectionStation.getStationId());
			eq.setStationName(currentInspectionStation.getStationName());	
			//默认问题数量为1
			eq.setQuestionAmount(1);
			eq.setPlanId(planId);
			eq.setQuesDeduct(eq.getQuestionAmount()* Float.parseFloat(deductionCriteria));
			InspectionItem item = deductService.getInspectionItemById(inspectionStationId, itemId);
			if(null != item) {
				InspectionItem pItem = item.getParent();
				if(null != pItem) {
					eq.setRiskLevel(pItem.getRiskLevel());
				}
			}
			quesEquipments.add(eq);
			equipmentAndNewImageMap.put(eq, new ArrayList<RecordImageDTO>());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取当前InspectionItem所对应的问题设备，以及问题设备上传的图片或视频
	 * @param id
	 */
	private void genEquipmentAndImageMap() {
		equipmentAndNewImageMap = new HashMap<InspectionQuestionEquipment, List<RecordImageDTO>>();
		try {
			// 当前InspectionItem的所有问题设备
			List<InspectionQuestionEquipment> qes = equipmentService.findByInspectionItem(currentInspectionItem.getId());
			for (InspectionQuestionEquipment qe : qes) {
				equipmentAndNewImageMap.put(qe, new ArrayList<RecordImageDTO>());
			}
		} catch (Exception e) {
			e.printStackTrace();
			addErrorMessage("查找问题设备出错");
		}
	}
	
	public void preUploadImage(InspectionQuestionEquipment qe) {
		newImageDtos = equipmentAndNewImageMap.get(qe);
		if(null == newImageDtos) {
			newImageDto = new RecordImageDTO();
		}
		newImageDto = new RecordImageDTO();
		newImageDto.setId(ObjectId.get().toString());
		newImageDto.setOid(qe.getId());
		PersonnelEntityBean user = getCurrentUser();
		if(null != user) {
			newImageDto.setCreator(user.getCode());
		}
	}
	/**
	 * 上传图片
	 * @param event
	 */
	public void handleImageFileUpload(FileUploadEvent event) {
		UploadedFile file = event.getFile();
		String fileName = file.getFileName();
		byte[] content = file.getContents();
		String imageContents = new String(Base64.encodeBytes(content));
		newImageDto.setImageStr(imageContents);
		newImageDto.setName(fileName);
		newImageDto.setType(AttachmentType.PICTURE);
		newImageDtos.add(newImageDto);
	}
	/**
	 * 上传视频
	 * @param event
	 */
	public void handleVideoFileUpload(FileUploadEvent event) {
		UploadedFile file = event.getFile();
		String fileName = file.getFileName();
		byte[] content = file.getContents();
		String imageContents = new String(Base64.encodeBytes(content));
		newImageDto.setImageStr(imageContents);
		newImageDto.setName(fileName);
		newImageDto.setType(AttachmentType.VIDEO);
		newImageDtos.add(newImageDto);
	}
	/**
	 * 根据问题设备删除图片
	 * @return
	 */
	public void deleteImageByQuesEquipment(InspectionQuestionEquipment qe) {
		if(null != qe && StringUtils.isNotEmpty(qe.getId())) {
			try {
				docService.deleteImageByObjectId(qe.getId());
			} catch (Exception e) {
				e.printStackTrace();
				addErrorMessage("删除当前问题设备的相关图片出错");
			}
		}
	}

	public List<InspectionQuestionEquipment> getQuesEquipments() {
		return quesEquipments;
	}


	public void setQuesEquipments(List<InspectionQuestionEquipment> quesEquipments) {
		this.quesEquipments = quesEquipments;
	}

	public List<ProtectionEquipment> getAllCims() {
		return allCims;
	}


	public void setAllCims(List<ProtectionEquipment> allCims) {
		this.allCims = allCims;
	}


	public List<String> getSelectMenu() {
		return selectMenu;
	}


	public void setSelectMenu(List<String> selectMenu) {
		this.selectMenu = selectMenu;
	}


	public String getDescData() {
		return descData;
	}


	public void setDescData(String descData) {
		this.descData = descData;
	}


	public List<String> getQuesList() {
		return quesList;
	}

	public void setQuesList(List<String> quesList) {
		this.quesList = quesList;
	}

	public List<String> getReasonList() {
		return reasonList;
	}

	public void setReasonList(List<String> reasonList) {
		this.reasonList = reasonList;
	}

	public List<String> getGradeList() {
		return gradeList;
	}

	public void setGradeList(List<String> gradeList) {
		this.gradeList = gradeList;
	}

	public List<String> getSourceList() {
		return sourceList;
	}

	public void setSourceList(List<String> sourceList) {
		this.sourceList = sourceList;
	}

	public String getQuesDevice() {
		return quesDevice;
	}

	public void setQuesDevice(String quesDevice) {
		this.quesDevice = quesDevice;
	}

	public int getQuesDeviceNum() {
		return quesDeviceNum;
	}

	public void setQuesDeviceNum(int quesDeviceNum) {
		this.quesDeviceNum = quesDeviceNum;
	}

	public InspectionStation getCurrentInspectionStation() {
		return currentInspectionStation;
	}

	public void setCurrentInspectionStation(InspectionStation currentInspectionStation) {
		this.currentInspectionStation = currentInspectionStation;
	}

	public String getDeductionCriteria() {
		return deductionCriteria;
	}

	public void setDeductionCriteria(String deductionCriteria) {
		this.deductionCriteria = deductionCriteria;
	}

	public String getAlertMsg() {
		return alertMsg;
	}

	public void setAlertMsg(String alertMsg) {
		this.alertMsg = alertMsg;
	}
	
	public TreeNode getRoot() {
		return root;
	}

	public void setRoot(TreeNode root) {
		this.root = root;
	}

	public TreeNode[] getSelectedNodes() {
		return selectedNodes;
	}

	public void setSelectedNodes(TreeNode[] selectedNodes) {
		this.selectedNodes = selectedNodes;
	}

	public String getEquipmentQuery() {
		return equipmentQuery;
	}

	public void setEquipmentQuery(String equipmentQuery) {
		this.equipmentQuery = equipmentQuery;
	}

	public InspectionQuestionEquipment getSelectedEquipment() {
		return selectedEquipment;
	}

	public void setSelectedEquipment(InspectionQuestionEquipment selectedEquipment) {
		this.selectedEquipment = selectedEquipment;
	}
	
}
